#!/usr/bin/env python
# -*- coding:utf-8 -*-

'''
author:shangchu.li
'''

import logging
import logging.handlers
import ctypes
import time, os, sys
import inspect
import datetime


__all__ = ["AsLogger"]

FOREGROUND_WHITE = 0x0007
FOREGROUND_BLUE = 0x01  # text color contains blue.
FOREGROUND_GREEN = 0x02  # text color contains green.
FOREGROUND_RED = 0x04  # text color contains red.
FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREEN

STD_OUTPUT_HANDLE = -11
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)


def set_color(color, handle=std_out_handle):
    bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
    return bool

def singleton(cls, *args, **kw):
    instances = {}
    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return _singleton


@singleton
class AsLogger():
    def __init__(self, logName=""):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)

        logging.Formatter.converter = time.gmtime

        fmt = logging.Formatter('%(levelname)s: %(message)s')
        sh = logging.StreamHandler()
        sh.setFormatter(fmt)
        self.logger.addHandler(sh)

        path = os.path.join(os.path.split(os.path.abspath(sys.argv[0]))[0], 'log')
        if not os.path.isdir(path):
            os.mkdir(path)
        now_data = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        if logName is None or logName == "":
            self.filePath = os.path.join(path, os.path.basename(sys.argv[0]).replace('.py', "")+"_"+now_data+".log")
        else:
            self.filePath = os.path.join(path, logName+"_"+now_data+".log")

        handler = logging.handlers.RotatingFileHandler(self.filePath, maxBytes=20*1024*1024, backupCount=50)
        formatter = logging.Formatter('%(process)d- %(levelname)s: %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    def __printfNow(self):
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

    def __getLogMessage(self, level, message):
        frame, filename, lineNo, functionName, code, unknowField = inspect.stack()[2]

        '''日志格式：[时间] [类型] [记录代码] 信息'''

        return "[{}] [{}] [{} - {} - {}]:{}".format(self.__printfNow(), level, filename, lineNo, functionName,
                                                      message)
    def getLogFileName(self):
        return self.filePath

    def debug(self, message, color=FOREGROUND_WHITE):
        set_color(color)

        message = self.__getLogMessage("debug", message)
        self.logger.debug(message)
        set_color(FOREGROUND_WHITE)

    def info(self, message, color=FOREGROUND_GREEN):
        set_color(color)

        message = self.__getLogMessage("info", message)
        self.logger.info(message)
        set_color(FOREGROUND_WHITE)


    def warn(self, message, color=FOREGROUND_YELLOW):
        set_color(color)
        message = self.__getLogMessage("warn", message)
        self.logger.warn(message)
        set_color(FOREGROUND_WHITE)

    def error(self, message, color=FOREGROUND_RED):
        set_color(color)
        message = self.__getLogMessage("error", message)
        self.logger.error(message)
        set_color(FOREGROUND_WHITE)

#
# if __name__ == "__main__":
#     logobj = AsLogger()
#     logobj.debug("errr")
#     logobj.info("info")
#     logobj.error("error")
#     logobj.warn("warn")